#!/bin/bash

# This is an example for extracting the GZipped objects/streams in the PDF file. Such streams
# are having the token /FlateDecode. The decoding procedure uses small Perl script that
# requires CPAN module "Compress:Zlib" installed on client computer.
#
# The decodign process is hardcoded for one specific PDF data only, attached in this example.
#
echo Extracting from position: ${1}
echo Length of extracted segment: ${2}
echo "Extracting the FlateDecode section ..."
STREAMS=`strings -a -n 6 -t d "${1}" | grep "stream" | grep -v "endstream" | cut -d's' -f1`
ENDSTREAMS=`strings -a -n 9 -t d "${1}" | grep "endstream" | cut -d'e' -f1`
i=0

echo $STREAMS > /tmp/stream_starts
echo $ENDSTREAMS > /tmp/stream_stops

i=0
for stream in $STREAMS
do
   START=`expr $stream + 7`
   index="entry${i}"
   echo $index
   case $index in
      "entry0") STOP=`awk ' {print $1} ' /tmp/stream_stops`;;
      "entry1") STOP=`awk ' {print $2} ' /tmp/stream_stops`;;
      "entry2") STOP=`awk ' {print $3} ' /tmp/stream_stops`;;
      "entry3") STOP=`awk ' {print $4} ' /tmp/stream_stops`;;
      "entry4") STOP=`awk ' {print $5} ' /tmp/stream_stops`;;
      "entry5") STOP=`awk ' {print $6} ' /tmp/stream_stops`;;
      "entry6") STOP=`awk ' {print $7} ' /tmp/stream_stops`;;
      "entry7") STOP=`awk ' {print $8} ' /tmp/stream_stops`;;
      "entry8") STOP=`awk ' {print $9} ' /tmp/stream_stops`;;
      "entry9") STOP=`awk ' {print $10} ' /tmp/stream_stops`;;
   esac
   LEN=`expr $STOP - $START`
   echo "Offset: ${START}, end at ${STOP}, length: ${LEN}"
   OUTFILE="object.${i}.out"
   i=`expr $i + 1`

   dd if=main.pdf bs=1 skip=${START} count=${LEN} of=obj.flatedecode 2>&1

	echo "Decoding the content ..."
	perl - ${OUTFILE} <<'__PERL__'
	use Compress::Zlib;
   my ($c,$o);
   my $of = shift;
	open( SRC, '<', 'obj.flatedecode' ) or die "cannot open file obj.flatedecode - $!";
	binmode SRC;
	read( SRC, $c, 1048576 ) or die "cannot read obj.flatedecode - $!";
	$o = uncompress($c);
   open( OUT, '>', $of ) or die "connot clobber output file - $!";
	print OUT $o;
   close OUT;
	close SRC;
__PERL__
done   

exit 0;
